<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>模拟路由</title>
    <script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
  </head>
  <body>
    <div id="app">
      <!-- 通过超链接提供切换组件 -->
      <a href="#/index">主页</a>
      <a href="#/keji">科技</a>
      <a href="#/happy">娱乐</a>
      <a href="#/tiyu">体育</a>
      <!-- component标签作为组件的占位符 -->
      <component :is="comName"></component>
    </div>
    <script>
      //声明需要展示的组件
      const index = {
        template: `<h1>主页:这个学期什么时候开学?</h1>`,
      };

      const keji = {
        template: `<h1>科技:出了疫苗再说?</h1>`,
      };

      const happy = {
        template: `<h1>娱乐:美国人很牛?</h1>`,
      };

      const tiyu = {
        template: `<h1>体育:中国足球出线?</h1>`,
      };

      //1. 实例化一个Vue的实例
      let vm = new Vue({
        el: "#app",
        data: {
          comName: "index",
        },
        components: {
          index,
          keji,
          happy,
          tiyu,
        },
      });

      // 通过window中onhashchange事件,当hash值变化,会触发对应的函数
      window.onhashchange = function () {
        //通过location.hash获得最新的hash值
        console.log(location.hash); // #/keji
        switch (location.hash.slice(1)) {
          case "/index":
            vm.comName = "index";
            break;
          case "/keji":
            vm.comName = "keji";
            break;
          case "/happy":
            vm.comName = "happy";
            break;
          case "/tiyu":
            vm.comName = "tiyu";
            break;
        }
      };
    </script>
  </body>
</html>
